const moment = require('moment');
const { Op } = require('sequelize');
let TEST = false;
// TEST = true;

module.exports = function (app, opts) {
  const recoverWorkOrder = app.fs.scheduleInit(
    {
      interval: '10 10 0 * * *', //每天0点10分10秒执行
      immediate: false
      // proRun: !TEST,
    },
    async () => {
      const transaction = await app.fs.dc.orm.transaction();
      try {
        const { models } = app.fs.dc;
        const sequelize = app.fs.dc.orm;
        //将挂起的任务进行回收
        const workOrder = await models.WorkOrderManagement.findAll({
          attributes: ['id'],
          where: {
            status: 3,
          },
          include: [
            {
              model: models.WorkOrderInstance,
              attributes: ['id'],
              where: {
                handleTime: {
                  //处理时间小于了当前时间
                  $lt: moment().format('YYYY-MM-DD HH:mm:ss'),
                },
              },
            },
          ],
        });
        let managementIds = [];
        let instanceIds = [];
        for (let i = 0; i < workOrder.length; i++) {
          if (!managementIds.some((item) => item === workOrder[i].id)) {
            managementIds.push(workOrder[i].id);
          }
          for (let j = 0; j < workOrder[i].workOrderInstances.length; j++) {
            if (!instanceIds.some((item) => item === workOrder[i].workOrderInstances[j].id)) {
                instanceIds.push(workOrder[i].workOrderInstances[j].id);
            }
          }
        }

        await models.WorkOrderManagement.update(
          { status: 1 },
          { where: { id: { $in: [...managementIds,-1] } }, transaction }
        );
        await models.ManagementInstance.destroy({ where: { instanceId: { $in: [...instanceIds,-1] } }, transaction });
        await models.WorkOrderInstance.destroy({ where: { id: { $in: [...instanceIds,-1] } }, transaction });
        await transaction.commit();
      } catch (error) {
        await transaction.rollback();
        console.error('Error in recoverWorkOrder:', error);
        app.fs.logger.error(`schedule: recoverWorkOrder, error: ${error}`);
      }
    }
  );

  return {
    recoverWorkOrder,
  };
};
